<template>
  <view class="code-container">
    <view class="artworks-sort-tips">
      <text>*注：最多支持设置8个口令哦~</text>
      <view class="back-btn" @click="goBack">
        <!-- <u-icon name="plus" color="#56d39d" size="24"></u-icon> -->
        <text class="huiju-iconfont huiju-icon-fanhui1"></text>
        <text>返回</text>
      </view>  
    </view>
    <view
      v-for="item in codeInfo.codeList"
      :key="item.id"
      class="code-item">
      <view class="code-content">{{ item.code }}</view>
      <!-- 达人主页信息 -->
      <view class="author-info" @click="handleSelectAuthorHome(item)">
        <image
          :src="item.authorInfo ? item.authorInfo.avatar : 'https://qiniu-res.jintianwang.cc/20221106164424-default_avatar.png'"
          mode="aspectFit"
          class="author-avatar"
        />
        <view class="author-name">{{ item.authorInfo ? item.authorInfo.name : '暂无' }}</view>
        <view>
          <u-icon name="play-right-fill" size="24" color="#9695a8"></u-icon>
        </view>
      </view>
      <!-- 默认显示类别 -->
      <view class="author-info" @click="handleSelectAuthorHome(item)">
        <view class="type-name">{{ item.artworksTypeInfo ? item.artworksTypeInfo.type_name : '全部' }}</view>
        <view>
          <u-icon name="play-right-fill" size="24" color="#9695a8"></u-icon>
        </view>
      </view>
      <!-- 删除按钮 -->
      <view class="deletc-icon" @click="handleDeleteCode(item)">
        <text class="huiju-iconfont huiju-icon-shanchu"></text>
      </view>
    </view>
    <!-- 创建口令 -->
    <view class="create-code">
      <u-button
        class="btn"
        type="primary"
        shape="circle"
        hover-class="none"
        :custom-style="{
          backgroundColor: '#56d39d',
          fontWeight: 700
        }"
        @click="handleCreateCode">创建口令</u-button>
    </view>
    <!-- 选择创作者关联口令 -->
    <u-select
      v-model="authorSelect.showAuthorHomeSelect"
      mode="mutil-column-auto"
      :list="author.authorList"
      :default-value="authorSelect.defaultValue"
      label-name="name"
      value-name="id"
      confirm-color="#56d39d"
      @confirm="confirm"></u-select>
    
    <!-- 提示 -->
    <u-modal
      v-model="authorSelect.showTip"
      title="请注意"
      :title-style="{color: 'red'}"
      :show-cancel-button="true"
      confirm-color="#56d39d"
      @cancel="authorSelect.showTip = false"
      @confirm="submitUpdateCode">
      <view class="model-content">
				<view class="content-item">1.修改搜索码指向会导致用户无法通过之前的搜索码找到之前的页面。你确定要修改成最新的页面指向吗？</view>
        <!-- <view>2.全部类型是不包含<text style="color: red">电视剧的展示类型</text>，电视剧请单独关联主页搜索码。</view> -->
			</view>
    </u-modal>

    <!-- 创建口令 -->
    <u-modal
      ref="createCodeModal"
      v-model="createCode.show"
      :show-title="false"
      :title-style="{color: '#333'}"
      :show-cancel-button="true"
      confirm-color="#56d39d"
      :negative-top="150"
      :async-close="true"
      @cancel="createCode.showTip = false"
      @confirm="confirmCreateCode()">
      <view class="create-content">
				<u-form :model="createCode" ref="uForm" label-width="150">
          <u-form-item label="页面口令" prop="code" :border-bottom="false">
            <u-input v-model="createCode.code" maxlength="8" border placeholder="请输入页面口令"></u-input>
            <u-button slot="right" size="mini" type="primary" hover-class="none" :custom-style="{
              backgroundColor: '#56d39d'
            }" @click="handleCheckCode">检测</u-button>
          </u-form-item>
        </u-form>
			</view>
    </u-modal>
  </view>
</template>

<script>
import { codeByUserId, authorInfoByUserId, updateCodeLimitAuthor, checkCode, createCode, deleteCode } from '@/api/artworks';
import { mapGetters } from 'vuex';
export default {
  data() {
    return {
      codeInfo: {
        codeList: []
      },
      author: {
        authorList: []
      },
      authorSelect: {
        showTip: false,
        showAuthorHomeSelect: false,
        defaultValue: []
      },
      changeForm: {
        id: '',
        author_id: '',
        recommend_artworks_type: ''
      },
      artworksTypelistData: [],
      createCode: {
        show: false,
        code: ''
      },
      code_type: '1'
    }
  },
  onLoad() {
    this.getCodeList();
    this.getArtworksTypeAllList();
  },
  computed: {
    ...mapGetters([
      'artworksTypeAllListData',
    ])
  },
  methods: {

    // 删除口令
    handleDeleteCode(itemData) {
      uni.showModal({
        title: '确认删除',
        content: `确定删除该“${itemData.code}”页面口令吗？删除口令将会导致用户无法通过此口令找到页面，请您熟知。`,
        confirmText: '确定',
        cancelText: '取消',
        confirmColor: '#56d39d',
        success: ({ confirm, cancel }) => {
          if (confirm) {
            deleteCode({
              id: itemData.id
            }).then(result => {
              if (result && result.code === 200) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'none',
                });
                this.getCodeList();
              } else {
                uni.showToast({
                  title: '删除成功，请重试',
                  icon: 'none',
                });
              }
            })
          }
        }
      })
    },

    // 点击添加口令
    handleCreateCode() {
      const codeInfoLength = this.codeInfo.codeList.length;
      if (codeInfoLength >= 8) {
        uni.showToast({
          title: '口令最多添加8个，请删除在重新添加。',
          icon: 'none',
        })
        return;
      }
      this.createCode.show = true
    },

    // 创建口令
    confirmCreateCode() {
      if (!this.createCode.code) {
        uni.showToast({
          title: '页面口令不能为空！',
          icon: 'none',
          mask: false,
        })
        this.$refs.createCodeModal.clearLoading();
        return;
      }
      // 新增校验
      if (!/^[\da-z]+$/i.test(this.createCode.code)) {
        uni.showToast({
          title: '口令仅支持数字或字母组合',
          icon: 'none',
        });
        this.$refs.createCodeModal.clearLoading();
        return;
      }
      uni.showToast({
        title: '提交中...',
        icon: 'loading',
        mask: true,
      })
      createCode({
        code: this.createCode.code,
        code_type: this.code_type
      }).then(result => {
        if (result && result.code === 200) {
          this.createCode.show = false;
          uni.showToast({
            title: '添加成功',
            icon: 'none',
          });
          this.getCodeList();
        } else {
          uni.showToast({
            title: '添加失败，请重试',
            icon: 'none',
          });
        }
      })
    },

    // 检测口令是否可用
		handleCheckCode() {
      if (!this.createCode.code) {
        uni.showToast({
          title: '页面口令不能为空！',
          icon: 'none',
          mask: false,
        })
        return;
      }
      // 新增校验
      // if (!/^[\da-z]+$/i.test(this.createCode.code)) {
      //   uni.showToast({
      //     title: '口令仅支持数字或字母组合',
      //     icon: 'none',
      //   });
      //   return;
      // }
      uni.showToast({
        title: '检测中...',
        icon: 'loading',
        mask: true,
      })
      checkCode({
        code: this.createCode.code
      }).then(result => {
        console.log(result);
        if (result && !result.data) {
          uni.showToast({
            title: '恭喜你，该口令可用',
            icon: 'none',
          })
        } else {
          uni.showToast({
            title: '口令已存在或不可用，请重新输入',
            icon: 'none',
          })
        }
      })
    },

    // 确定选择关联
    confirm(val) {
      this.changeForm.author_id = val[0].value;
      this.changeForm.recommend_artworks_type = val[1].value;
      this.authorSelect.showTip = true;
    },

    // 提交修改关联
    submitUpdateCode() {
      updateCodeLimitAuthor(this.changeForm).then(result => {
        if (result && result.code === 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'none',
          });
          this.getCodeList();
        } else {
          uni.showToast({
            title: '删除失败，请重试',
            icon: 'none',
          });
        }
      })
    },

    // 选择关联的创作者
    handleSelectAuthorHome(itemData) {
      let authorIndex = 0;
      if (itemData.authorInfo) {
        authorIndex = this.author.authorList.findIndex(item => item.id === itemData.authorInfo.id);
      }
      let artworksTypeIndex = 0;
      if (itemData.artworksTypeInfo) {
        artworksTypeIndex = this.artworksTypelistData.findIndex(item => item.id === itemData.artworksTypeInfo.id);
      }
      this.authorSelect.defaultValue = [ authorIndex, artworksTypeIndex ];
      this.authorSelect.showAuthorHomeSelect = true;
      this.changeForm.id = itemData.id;
    },

    // 获取code信息列表
    getCodeList() {
      codeByUserId({
        code_type: this.code_type
      }).then(result => {
        if (result && result.data && result.data.length > 0) {
          let list = result.data;
          list.forEach(item => {
            if (item.recommend_artworks_type == 100) {
              item.artworksTypeInfo = {
                id: 100,
                type_name: '专辑'
              }
            } else if (item.recommend_artworks_type == 101) {
              item.artworksTypeInfo = {
                id: 101,
                type_name: '定制中心'
              }
            }
          })
          this.codeInfo.codeList = result.data;
        }
      })
    },

    // 根据用户id获取全部的达人主页信息
    getAuthorInfoByUserId() {
      authorInfoByUserId({
        show_make: this.code_type
      }).then(result => {
        if (result && result.data && result.data.length > 0) {
          let list = result.data;
          if (this.artworksTypelistData && this.artworksTypelistData.length > 0) {
            list.forEach(item => {
              item.children = this.artworksTypelistData;
            })
          }
          this.author.authorList = list;
        }
      })
    },

    // 获取作品类型
    getArtworksTypeAllList() {
      let list = this.artworksTypeAllListData.map(item => {
        return {
          name: item.type_name,
          id: item.id
        }
      });
      this.artworksTypelistData = [
        ...[{ name: '全部', id: '' }],
        ...list,
        ...[{ name: '专辑', id: 100 }, { name: '定制中心', id: 101 }],
      ];
      this.getAuthorInfoByUserId();
    },

    // 返回
    goBack() {
      let pages = getCurrentPages();
      let pagesLength = pages.length;

      if (pagesLength > 1) {
        uni.navigateBack({
          delta: 1,
        })
      } else {
        uni.switchTab({ url: '/pages/creativeCenter/index' });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
page{
  background-color: #f5f5f5;
}
.code-container{
  padding: 100rpx 24rpx 220rpx 24rpx;

  .artworks-sort-tips{
    color: $uni-color-primary;
    background-color: #f3f7fb;
    padding: 24rpx 32rpx;
    font-size: 24rpx;
    border-radius: 8rpx;
    margin-bottom: 24rpx;
    width: 100%;
    /* #ifdef H5 */
    max-width: 375px;
    margin: auto;
    /* #endif */
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1000;
  }

  .back-btn{
    position: absolute;
    right: 32rpx;
    top: 0;
    bottom: 0;
    margin: auto;
    font-size: 26rpx;
    color: $uni-color-primary;
    background: #fff;
    padding: 0 24rpx;
    border-radius: 24rpx;
    height: 48rpx;
    line-height: 48rpx;
  }

  .code-item{
    padding: 32rpx 24rpx;
    box-shadow: 0rpx 1rpx 10rpx 2rpx #d5dcf0;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    background: #fff;
    margin-bottom: 32rpx;

    .code-content{
      width: 160rpx;
      font-size: 28rpx;
      font-weight: 500;
      color: #333;
      padding-right: 12rpx;
      position: relative;

      &::before{
        content: "";
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        margin: auto;
        width: 2rpx;
        height: 32rpx;
        background: #e9e9e9;
      }
    }

    .author-info{
      background: #f7f7f7;
      margin-left: 24rpx;
      padding: 8rpx 12rpx;
      border-radius: 36rpx;
      display: flex;
      align-items: center;
      
      .author-avatar{
        width: 48rpx;
        height: 48rpx;
        border-radius: 50%;
        margin-right: 6rpx;
      }

      .author-name{
        width: 100rpx;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        font-size: 28rpx;
        color: #9695a8;
      }

      .type-name{
        width: 154rpx;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        font-size: 28rpx;
        color: #9695a8;
      }
    }

    .deletc-icon{
      text-align: right;
      width: 50rpx;
      height: 50rpx;
      line-height: 50rpx;
      color: $uni-color-primary;
      font-size: 32rpx;
    }
  }

  .code-tip{
    font-size: 20rpx;
    color: #9695a8;
  }

  .create-code{
    position: fixed;
    padding: 32rpx 0;
    bottom: 60rpx;
    left: 0;
    right: 0;
    margin: auto;
    width: 320px;
  }
}

.model-content{
  padding: 32rpx;
  font-size: 28rpx;
  color: #333;

  .content-item{
    margin-bottom: 12rpx;
  }
}

.create-content{
  padding: 32rpx;
}
</style>
